package cn.yeyiu.util;

import android.content.Context;
import cn.yeyiu.util.bean.TimeVideoInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import okhttp3.HttpUrl;

public class ExternalJSONFile {
    public static String favour = "favour";
    public static String net = "net";
    public static String path = "data/";
    public static String recent = "recent";
    private Context mContext;

    public void load(String str) {
    }

    public void save() {
    }

    public static ExternalJSONFile with(Context context) {
        ExternalJSONFile externalJSONFile = new ExternalJSONFile();
        externalJSONFile.mContext = context;
        return externalJSONFile;
    }

    // 写入json list
    public static void writeArray(Context context, String type, JSONArray jSONArray) {
        save(context, type, jSONArray.toJSONString());
    }

    // 附加json list
    public static void appendObj(Context context, String type, Object obj) {
        JSONArray jSONArray;
        String load = load(context, type);
        if (load == null || "".equals(load)) {
            jSONArray = new JSONArray();
        } else {
            jSONArray = JSONArray.parseArray(load);
        }
        jSONArray.add(obj);
        writeArray(context, type, jSONArray);
    }

    // 加载json
    public static String load(Context context, String type) {
        try {
            String str2 = context.getExternalFilesDir(null).getPath() + "/" + type + ".json";
            File file = new File(str2);
            if (!file.exists()) {
                file.createNewFile();
                return null;
            }
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(str2), StandardCharsets.UTF_8));

            StringBuilder sb = new StringBuilder();
            String tmpLine;
            while ((tmpLine=reader.readLine())!=null) {
                sb.append(tmpLine);
            }
            reader.close();
            String json = sb.toString();
            if ("".equals(json)) {
                return null;
            }
            return json;
        } catch (Exception unused) {
            return null;
        }
    }

    // 保存为json
    public static void save(Context context, String type, String json) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(
                    context.getExternalFilesDir("")
                            .getPath() + "/" + type + ".json");
            fileOutputStream.write(json.getBytes(StandardCharsets.UTF_8));
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean exist(Context context, String type){
        try {
            File file = new File(
                    context.getExternalFilesDir("")
                            .getPath() + "/" + type + ".json");
            return file.exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 删除json 单条记录
    public static void remove(Context context, String type, int i) {
        JSONArray jSONArray;
        // read
        String load = load(context, type);
        if (load == null || "".equals(load)) {
            jSONArray = new JSONArray();
        } else {
            jSONArray = JSONArray.parseArray(load);
        }
        jSONArray.remove(i);
        // update
        save(context, type, jSONArray.toJSONString());
    }

    // 删除json 特定关键字记录
    public static void remove(Context context, String type, String title) {
        JSONArray jSONArray;
        // read
        String load = load(context, type);
        if (load == null || "".equals(load)) {
            jSONArray = new JSONArray();
        } else {
            jSONArray = JSONArray.parseArray(load);
        }
        Iterator<Object> iterator = jSONArray.iterator();
        while (iterator.hasNext()){
            TimeVideoInfo o = ((JSONObject)iterator.next()).toJavaObject(TimeVideoInfo.class);
            if(title.equals(o.title)){
                iterator.remove();
            }
        }
        // update
        save(context, type, jSONArray.toJSONString());
    }

    // 保存ip记录
    public static void saveIp(Context context, String str) {
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("ip", (Object) str);
        save(context, net, jSONObject.toJSONString());
    }

    // 加载ip json
    public static String loadIp(Context context) {
        String load = load(context, net);
        if (load != null && !HttpUrl.FRAGMENT_ENCODE_SET.equals(load)) {
            System.out.println(load);
            JSONObject parseObject = JSONObject.parseObject(load);
            if (parseObject != null) {
                return parseObject.getString("ip");
            }
        }
        return null;
    }

    // 保存特定单条记录
    public static void saveDatas(Context context, String type, TimeVideoInfo timeVideoInfo) {
        appendObj(context, type, timeVideoInfo);
    }

    // 加载特定记录list: favour, recent ...
    public static List<TimeVideoInfo> loadDatas(Context context, String type) {
        String load = load(context, type);
        if (load == null) {
            return null;
        }
        return JSONArray.parseArray(load, TimeVideoInfo.class);
    }
}
